package com.invest.utils;

import java.io.IOException;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.List;

/**
 * @projectName: invest
 * @author: yuch
 * @description: TODO   计算可转债的纯债价值和回售收益率
 * @date: 2025/1/23 11:14
 */


public class CbDataUtil {


    /**
     * @param cPrice   现价
     * @param price    回售价格
     * @param interest 当年利息
     * @param date     回售日期
     */
    public static String getBackBondYield(String cPrice, String price, String interest, String date) {
        LocalDate backDate = LocalDate.parse(date);
        LocalDate currentDate = LocalDate.now();
        double backPrice = Double.parseDouble(price);
        double currentPrice = Double.parseDouble(cPrice);
        // 计算剩余期间的利息（税后）
        double taxAfterInterest = Double.parseDouble(interest);

        // 计算剩余年数
        double yearsRemaining = (double) ChronoUnit.DAYS.between(currentDate, backDate) / 365;

        // 计算期末市值
        double endMarketValue = backPrice + taxAfterInterest;

        // 计算年化税后回售收益率
        double yieldToPut = (endMarketValue - currentPrice) / (currentPrice * yearsRemaining);
        // 转换为百分比
        double yieldToPutPercentage = yieldToPut * 100;

        return yieldToPutPercentage + "";
    }




    /**
     * 计算转债的纯债价值
     *
     * @param rates 可转债利息
     * @param price   到期赎回价格
     * @param year  剩余年限
     * @return   可转债的纯债价值
     * @throws IOException
     */
    public static String getpureBondPrice(List<String> rates, String price, String year,Double riskfree) throws IOException {
        double[] interestRates = rates.stream().mapToDouble(s -> Double.parseDouble(s) / 100).toArray();// 每年的利率
        double redemptionPrice = Double.parseDouble(price); // 转债到期赎回价格
        double yearsRemaining = Double.parseDouble(year); //
        double riskFreeRate = riskfree = riskfree == null ? riskfree : 0.02; // 无风险利率
        double pureBondPrice = 0;
        // 计算剩余年限内的利息现值
        int y = interestRates.length - 1;
        for (double i = yearsRemaining; i > 0; i--, y--) {
            if (i == yearsRemaining) {
                //最后一年
                double redemptionDiscountFactor = 1 / Math.pow(1 + riskFreeRate, yearsRemaining);
                pureBondPrice += redemptionPrice * redemptionDiscountFactor; // 累加到期赎回现值
                continue;
            }
            double cashFlow = 100 * interestRates[y];
            double discountFactor = 1 / Math.pow(1 + riskFreeRate, i); // 折现因子
            pureBondPrice += cashFlow * discountFactor; // 累加现值

        }
        // 计算到期赎回价格的现值
        double redemptionCashFlow = redemptionPrice; // 到期赎回现金流
        // 到期赎回折现因子

        return pureBondPrice + "";
    }


    /**
     * 税前到期收益率的计算
     */

}
